#include <list>
#include "AcceptedFlow.h"


AcceptedFlow::AcceptedFlow() : ThreadProcess("AcceptedFlow")
{

}
UDPSenderPointer AcceptedFlow::find(FlowID const& flowID)
{
	pthread_mutex_lock(&m_lock);
	FlowIDvsFilterID::iterator itr(m_accepted.find(flowID));

	if(itr != m_accepted.end())
	{
		UDPSenderPointer sender(itr->second);
		pthread_mutex_unlock(&m_lock);
		return sender;
	}

	pthread_mutex_unlock(&m_lock);
	return UDPSenderPointer();
}
void AcceptedFlow::clean(FlowID const& flowID)
{
	pthread_mutex_lock(&m_lock);
	m_accepted.erase(flowID);
//                      std::cout << "erase=" << flowID << std::endl;
	pthread_mutex_unlock(&m_lock);
}
void AcceptedFlow::add(FlowID const& flowID, UDPSenderPointer& filterID)
{
	pthread_mutex_lock(&m_lock);
	m_accepted[flowID] = filterID;

	FlowClean clean;
	clean.flowID = flowID;
	clean.time = time(0);
	m_usedList.push(clean);
	pthread_mutex_unlock(&m_lock);
}
bool AcceptedFlow::isClean()
{
	return m_usedList.empty() & m_accepted.empty();
}
bool AcceptedFlow::process()
{
	sleep(1);
	while (!m_usedList.empty())
	{
		FlowClean flowClean = m_usedList.front();

		if(difftime(time(0), flowClean.time) > 2)
		{
			clean(flowClean.flowID);
			m_usedList.pop();
		}
		else
		{
			break;
		}
	}
	return true;
}
